import  { useEffect, useLayoutEffect, useRef } from "react";
import "./index.less";
import { createPortal } from "react-dom";
import { Form, Input, Button, Row, Col } from "antd";
import {  useSlate } from "slate-react";
import  debounce from 'lodash.debounce'
export type ModalProps = {
  onConfirm?: Function;
  defaultValue?: any;
  open?:boolean;
  onClose?: Function;
};

export default (props: ModalProps) => {
  const { open, onConfirm, defaultValue={}, onClose } = props;
  const ref = useRef<any>();
  const [form] = Form.useForm();
  const editor: any = useSlate();
  const move=debounce(()=>{
    const el = ref.current;
    if(el&&open&&editor.selection){
  
        const domSelection = window.getSelection();
        console.log(domSelection);
  
        const domRange = domSelection?.anchorNode
          ? domSelection?.getRangeAt?.(0)
          : null;
        if (domRange) {
          const rect = domRange.getBoundingClientRect();
          let y = rect?.top + rect.height + window.scrollY;
          const x = rect?.left + rect.width / 2 + window.scrollX;
  
          el.style.display = "block";
          el.style.transform = `translate3d(${x}px,${y}px,0)`;
        } else {
          el.style.display = "none";
        }
      
    }
  },300)

  useLayoutEffect(() => {
     move()
  });

  useEffect(() => {
      form?.setFieldsValue?.(defaultValue);
   
   
  }, [defaultValue]);

  const onFinish = (values: any) => {
    onConfirm?.(values);
  };

  useEffect(()=>{
    if(!open){
      form?.setFieldsValue?.({text:null,url:null});
    }

  },[open])

 const currentClose=()=>{
   onClose?.();
 }

  const onDocumentClick = (event:MouseEvent) => {
    const current_node = event.target;
    const $modal = ref.current;
    if (!$modal?.contains(current_node)) {
    
      currentClose()
    }
  };

  useLayoutEffect(() => {
    let timer:any=null;

    if(open){
      timer=setTimeout(()=>{
        document.addEventListener("click", onDocumentClick);
      },200)
    }else{
      document.removeEventListener("click", onDocumentClick);
   }
    return () => {
      if(timer){
        clearTimeout(timer)
      }
     
      document.removeEventListener("click", onDocumentClick);
    };
  }, [open]);

  if (!open) {
    return null;
  }

  return <>{createPortal(
    <div className="modal">
      <div ref={ref}  className="editor-modal">
        <Form onFinish={onFinish} labelCol={{ span: 6 }} form={form}>
          <Row>
            <Col span={18}>
              <Form.Item label="文字" name="text" rules={[{ required: true }]}>
                <Input autoFocus></Input>
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={18}>
              <Form.Item
                label="链接"
                name="url"
                rules={[{ required: true }, { type: "url" }]}
              >
                <Input></Input>
              </Form.Item>
            </Col>
            <Col span={5} offset={1}>
              <Form.Item>
                <Button type="primary" htmlType="submit">
                  确认
                </Button>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </div>
    </div>,
    document.querySelector("body") as HTMLElement
  )}
  </>
};
